﻿using System;
using System.Windows.Forms;
using Tao.Platform.Windows;
using System.Collections.Generic;

namespace proba_pera
{
    public class UnitsController:RwpBaseObject
    {
        List<Waypoint> _list;
        private readonly Collector _rwpCollector;
        public Ways Ways;
        private readonly Visualiser _rwpVisualiser;
// ReSharper disable NotAccessedField.Local
        private int _selectedUnitId;
// ReSharper restore NotAccessedField.Local
        private RwpUnit _selectedUnit;
        //private readonly List<RwpUnit> _selectedUnitsCollection; 
        private readonly bool _multipleSelection;
// ReSharper disable NotAccessedField.Local
        private int _mainUserId;
// ReSharper restore NotAccessedField.Local
        private readonly SimpleOpenGlControl _cntrl;
        private bool _leftButton;
        private double _regionStartX, _regionStartY;
        private bool _isSetWaypoints;
        private int _lastCoordX;
        private int _lastCoordY;

        public UnitsController(Visualiser rwpVisualiser, Collector col, SimpleOpenGlControl cntrl, int mainUserId, bool multiple)
        {
            _lastCoordX = 0;
            _lastCoordY = 0;
            _rwpCollector = col;
            Ways = new Ways(_rwpCollector);
            _selectedUnitId = 0;
            _selectedUnit = null;
            _multipleSelection = multiple;
            _mainUserId = mainUserId;
            _cntrl = cntrl;
            
            _leftButton = false;
//            _selectedUnitsCollection = new List<RwpUnit>(); 
            _regionStartX = -1;
            _regionStartY = -1;
            _rwpVisualiser = rwpVisualiser;
            cntrl.MouseClick += Clickevent;
            cntrl.MouseMove += Selectregionevent;
            cntrl.MouseDown += Mousedownevent;
            cntrl.MouseUp += Mouseupevent;
            cntrl.KeyPress += Keydownevent;
            //_selectedUnit = _rwpCollector.GetList().Last();
        }

        public void SelectUnit(int id)
        {
            _selectedUnitId = id;
            _selectedUnit = _rwpCollector.GetById(id);
            //_selectedUnitsCollection.Clear();
            //_selectedUnitsCollection.Add(_rwpCollector.GetById(id));
        }

        public void Keydownevent(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 'w' || e.KeyChar == 'W')
                _rwpVisualiser.MoveFrame(0, -1);
            if (e.KeyChar == 's' || e.KeyChar == 'S')
                _rwpVisualiser.MoveFrame(0, 1);
            if (e.KeyChar == 'a' || e.KeyChar == 'A')
                _rwpVisualiser.MoveFrame(-1, 0);
            if (e.KeyChar == 'd' || e.KeyChar == 'D')
                _rwpVisualiser.MoveFrame(1, 0);
        }

        public void Clickevent(object sender, MouseEventArgs e)
        {
            int newCoordX = Convert.ToInt32(Math.Floor(Convert.ToDouble(e.X)) / 15 - 0.5);
            int newCoordY = Convert.ToInt32(Math.Floor(Convert.ToDouble(_cntrl.Height - e.Y) / 15));
           
            //MessageBox.Show(e.X.ToString() + e.Y.ToString());
            if (e.Button == MouseButtons.Left)
            {
                //убираем выделение с выбранного до этого юнита
                if (_selectedUnit != null)
                {
                    _selectedUnit.Selected = false;
                    string str = "Unselected" + _selectedUnit.GetId() + "; X: " + _selectedUnit.GetX() + "; Y: " +
                                 _selectedUnit.GetY(); 
                    ToLog(str);
                }
                //меняем выбраный юнит по установленным курсором координатам
                _selectedUnit = _rwpCollector.SelectByXy(newCoordX, newCoordY);
                if (_selectedUnit != null)
                {
                    string str = "Select unit! Id: " + _selectedUnit.GetId() + "; X: " + _selectedUnit.GetX() + "; Y: " +
                                 _selectedUnit.GetY();
                    ToLog(str);
                }
                else
                {
                    string str = "Empty click. X: " +newCoordX.ToString()+ " ; Y: "+newCoordY.ToString();
                    ToLog(str);
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                if (_selectedUnit==null) return;
                if (_isSetWaypoints == false || (_lastCoordX != newCoordX || _lastCoordY != newCoordY))
                {
                    _list = new List<Waypoint>(Ways.Getlist((int)_selectedUnit.GetX(), (int)_selectedUnit.GetY(), newCoordX, newCoordY));
                    _isSetWaypoints = true;
                    _rwpVisualiser.SetWay(_list);
                    foreach (var waypoint in _list)
                    {
                        string strlist = "step: " + waypoint.X + "/" + waypoint.Y;
                        ToLog(strlist);
                    }
                    _lastCoordX = newCoordX;
                    _lastCoordY = newCoordY;
                    string str = "Setting waypoints. Selected unit id: " + _selectedUnit.GetId() + ",";
                    ToLog(str);
                    str = "-->X start: " + _selectedUnit.GetX() + "; Y start: " +
                              _selectedUnit.GetY() + "; X end: " + newCoordX.ToString() + "; X end: " + newCoordY.ToString()+";"; 
                    ToLog(str);
                }
                else if(_lastCoordX == newCoordX &&  _lastCoordY == newCoordY)
                {
                    _selectedUnit.SetWaypoints(_list);
                    _isSetWaypoints = false;
                }
            }
        }

        public void Selectregionevent(object sender, MouseEventArgs e)
        {
            if (_cntrl!=null&&_regionStartX>-1&&_regionStartY>-1)
            {
                double newCoordX = Convert.ToDouble(e.X) / 15;
                double newCoordY = Math.Abs(Convert.ToDouble(_cntrl.Height - e.Y) / 15);
                if (_leftButton)
                {
                    _rwpVisualiser.SetSelectedRegion(_regionStartX, _regionStartY, newCoordX, newCoordY);
                }
            }
        }
        

        public void Mousedownevent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _regionStartX = Convert.ToDouble(e.X)/15;
                _regionStartY = Math.Abs(Convert.ToDouble(_cntrl.Height - e.Y)) / 15;
                _leftButton = true;
                _rwpVisualiser.SetSelectedRegion(_regionStartX, _regionStartY, _regionStartX, _regionStartY);
            }
            
        }

        public void Mouseupevent(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _leftButton = false;
                //_selectedUnit.Selected = false;
                double newCoordX = Convert.ToDouble(e.X) / 15 - 0.5;
                double newCoordY = Math.Abs(Convert.ToDouble(_cntrl.Height - e.Y)) / 15;
                if (_regionStartX!=newCoordX&&_regionStartY!=newCoordY)
                {
                    SelectRegion(_regionStartX, _regionStartY, newCoordX, newCoordY);
                }
                _rwpVisualiser.UnsetSelectedRegion(); 
            }
        }
        

        private void SelectRegion(double startX, double startY, double endX, double endY)
        {
            //_selectedUnitsCollection.Clear();
            if (_selectedUnit != null)
            {
                _selectedUnit.Selected = false;
                _selectedUnit = null;
            }
            _selectedUnit = _rwpCollector.SelectRegionByXy(startX - _rwpVisualiser.GetStartX(), startY - _rwpVisualiser.GetStartY(), endX - _rwpVisualiser.GetStartX(), endY - _rwpVisualiser.GetStartY(), _multipleSelection);
        }
    }
}